package com.wlcb.jpower.chat.reply;

import com.wlcb.jpower.chat.entity.file.TbChatFile;
import com.wlcb.jpower.chat.service.file.ChatFileService;
import com.wlcb.jpower.constant.ChatConstant;
import com.wlcb.jpower.module.common.utils.SpringUtil;
import com.wlcb.jpower.utils.WxMpInstance;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author: liwenfei
 * @version: v2.0
 * @time: 2021/4/15 9:56
 * @desc: 全局消息返回实体
 */
@Data
@Slf4j
public class ReplyEntity {
    /**
     * 回复的数组对象
     */
    private List<ReplyBody> replyBodys;
    /**
     * 回复到那个公众号
     */
    private String appId;
    /**
     * 执行什么接口回复
     */
    private Integer replyType;
    /**
     * 目标用户
     */
    private String toUser;

    /**
     * 执行被动回复 没有什么用
     *
     * @return
     */
    public ReplyEntity normal() {
        this.replyType = 2;
        return this;
    }

    /**
     * 执行客服接口回复
     *
     * @return
     */
    public ReplyEntity kefu() {
        this.replyType = 1;
        return this;
    }

    /**
     * 封装一条文本消息
     *
     * @param content
     * @param isReply 是否发送
     * @return
     */
    public static ReplyEntity singleTextMessage(String content, Boolean isReply) {
        ReplyBody replyBody = new ReplyBody();
        replyBody.setType(ChatConstant.MessageTypeEnum.TEXT.type);
        replyBody.setContent(content);
        replyBody.setIsReply(isReply);
        ReplyEntity replyEntity = new ReplyEntity();
        replyEntity.setReplyBodys(Collections.singletonList(replyBody));
        return replyEntity;
    }

    /**
     * 发送消息的最终接口
     *
     * @throws WxErrorException
     */
    public void sendReply() throws WxErrorException {

        for (ReplyBody replyBody : this.replyBodys) {
            if (replyBody.getIsReply()) {
                switch (replyBody.getType()) {
                    //文本消息
                    case "text":
                        sendText(replyBody);
                        break;
                    //图片消息
                    case "image":
                        sendImage(replyBody);
                        break;
                    //视频消息
                    case "video":
                        sendVideo(replyBody);
                        break;
                    //菜单消息
                    case "msgmenu":
                        sendMenu(replyBody);
                        break;
                    //模板消息
                    case "tmsg":
                        sendTemplate(replyBody);
                        break;
                    default: {
                        log.error("不存在的消息类型");
                    }
                }
            }
        }

    }

    /**
     * 发送文本消息
     *
     * @param replyBody
     * @return
     * @throws WxErrorException
     */
    private boolean sendText(ReplyBody replyBody) throws WxErrorException {
        return wxMpService().getKefuService().sendKefuMessage(WxMpKefuMessage.TEXT().toUser(this.toUser).content(replyBody.getContent()).build());

    }

    /**
     * 发送图片消息
     *
     * @param replyBody
     * @return
     * @throws WxErrorException
     */
    private boolean sendImage(ReplyBody replyBody) throws WxErrorException {

        ChatFileService fileService = SpringUtil.getBean(ChatFileService.class);
        TbChatFile tbChatFile = fileService.findFile(replyBody.getImageId());
        File file = new File(tbChatFile.getFilePath());
        WxMediaUploadResult result = wxMpService().getMaterialService().mediaUpload(WxConsts.MaterialType.IMAGE, file);
        return wxMpService().getKefuService().sendKefuMessage(WxMpKefuMessage.IMAGE().toUser(this.toUser).mediaId(result.getMediaId()).build());
    }

    /**
     * 发送视频消息
     *
     * @param replyBody
     * @return
     * @throws WxErrorException
     */
    private boolean sendVideo(ReplyBody replyBody) throws WxErrorException {

        ChatFileService fileService = SpringUtil.getBean(ChatFileService.class);
        TbChatFile tbChatFile = fileService.findFile(replyBody.getImageId());
        File file = new File(tbChatFile.getFilePath());
        WxMediaUploadResult result = wxMpService().getMaterialService().mediaUpload(WxConsts.MaterialType.VIDEO, file);
        return wxMpService().getKefuService().sendKefuMessage(WxMpKefuMessage.VIDEO().toUser(this.toUser).mediaId(result.getMediaId()).build());
    }

    /**
     * 发送菜单消息
     *
     * @param replyBody
     * @return
     * @throws WxErrorException
     */
    private boolean sendMenu(ReplyBody replyBody) throws WxErrorException {

        List<WxMpKefuMessage.MsgMenu> msgMenus = new ArrayList<>();
        List<String> menus = replyBody.getMenus();
        for (String menu : menus) {
            WxMpKefuMessage.MsgMenu msgMenu = new WxMpKefuMessage.MsgMenu("123456", menu);
            msgMenus.add(msgMenu);
        }
        return wxMpService().getKefuService().sendKefuMessage(WxMpKefuMessage.MSGMENU()
                .msgMenus(msgMenus).toUser(toUser)
                .headContent(replyBody.getMenuHeader())
                .tailContent(replyBody.getMenuEnd()).build());

    }

    /**
     * 发送模板消息
     *
     * @param replyBody
     * @throws WxErrorException
     */
    private void sendTemplate(ReplyBody replyBody) throws WxErrorException {

        WxMpTemplateMessage message = new WxMpTemplateMessage();
        message.setToUser(this.toUser);
        message.setTemplateId(replyBody.getTemplateId());
        message.setUrl(replyBody.getTemplateUrl());
        List<TemplateBody> tBodys = replyBody.getTBodys();
        List<WxMpTemplateData> datas = new ArrayList<>();
        for (TemplateBody tBody : tBodys) {
            WxMpTemplateData data = new WxMpTemplateData();
            data.setName(tBody.getKey());
            data.setValue(tBody.getValue());
            data.setColor(tBody.getColor());
            datas.add(data);
        }
        message.setData(datas);
        wxMpService().getTemplateMsgService().sendTemplateMsg(message);

    }

    private WxMpService wxMpService() {
        return WxMpInstance.getWxMp().switchoverTo(this.appId);
    }

    @Data
    public static class ReplyBody {
        /**
         * 是否发送必填
         */
        @ApiModelProperty("是否发送")
        private Boolean isReply = true;
        /**
         * 消息类型必填 如;text image
         */
        @ApiModelProperty(value = "消息类型 text image video msgmenu tmsg",required = true)
        private String type;
        /**
         * text必填  文本内容必填
         */
        @ApiModelProperty(value = "文本内容 type=text必填")
        private String content;
        /**
         * image video必填   文件id
         */
        @ApiModelProperty(value = "文件id type=image、video必填")
        private String imageId;
        /**
         * 菜单消息必填 菜单消息头
         */
        @ApiModelProperty(value = "菜单消息头 type=msgmenu必填")
        private String menuHeader;
        /**
         * 菜单消息必填 菜单消息尾部
         */
        @ApiModelProperty(value = "菜单消息尾部 type=msgmenu必填")
        private String menuEnd;
        /**
         * 菜单消息必填 菜单消息body
         */
        @ApiModelProperty(value = "菜单消息body type=msgmenu必填")
        private List<String> menus;
        /**
         * 模板消息必填 模板id
         */
        @ApiModelProperty(value = "模板id type=tmsg必填")
        private String templateId;
        /**
         * 模板消息必填  点击模板跳转url
         */
        @ApiModelProperty(value = "点击模板跳转url type=tmsg必填")
        private String templateUrl;
        /**
         * 模板消息必填  模板小body
         */
        @ApiModelProperty(value = "模板小body type=tmsg必填")
        private List<TemplateBody> tBodys;
    }

    @Data
    public static class TemplateBody {
        /**
         * key值 如 first keyword1 keyword2 reamrk
         */
        @ApiModelProperty(value = "key值",required = true)
        private String key;
        /**
         * 具体的值
         */
        @ApiModelProperty(value = "具体的值",required = true)
        private String value;
        /**
         * 颜色  如：#173177
         */
        @ApiModelProperty(value = "颜色 如：#173177")
        private String color;
    }
}
